package cn.neusoft.servlet;


import cn.neusoft.bean.Cart;
import cn.neusoft.query.CartQuery;
import cn.neusoft.service.ICartService;
import cn.neusoft.service.impl.CartService;
import cn.neusoft.utils.IOUtils;
import cn.neusoft.utils.JsonUtils;
import cn.neusoft.vo.ResultBean;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-------CartSerclet------");
        ICartService cartService = new CartService();
        String what = req.getParameter("what");

        //最终的响应体对象
        ResultBean resultBean = null;

        try {
            if("save".equals(what)){
                System.out.println("添加或修改购物车");
                String jsonStr = IOUtils.readStr(req.getInputStream());
                Cart cart = JsonUtils.jsonStrToObj(jsonStr, "yyyy-MM-dd",Cart.class);
                if (cart.getCartId()==null){
                    resultBean = cartService.add(cart);
                }else {
                    resultBean = cartService.update(cart);
                }
            }else if("del".equals(what)){
                //http://localhost:8080/cart?what=del&id=1001
                System.out.println("删除购物车");
                String id = req.getParameter("id");
                resultBean = cartService.delete(Integer.parseInt(id));
            }else if("getById".equals(what)){
                System.out.println("通过id查询购物车");
                String id = req.getParameter("id");
                resultBean = cartService.getById(Integer.parseInt(id));
            }else if("page".equals(what)){
                System.out.println("分页搜索购物车");
                String jsonStr = IOUtils.readStr(req.getInputStream());
                CartQuery cartQuery = JsonUtils.jsonStrToObj(jsonStr, null, CartQuery.class);

                System.out.println("userId---"+cartQuery.getUserId());
                System.out.println("businessId---"+cartQuery.getBusinessId());
                resultBean = cartService.getByPage(cartQuery);
            }else{
                System.out.println("无服务");
                resultBean = ResultBean.ERROR("no service");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultBean = ResultBean.ERROR(e.getMessage());
        }

        //将resultBean转成json字符串响应即可
        String resultJsonStr = JSONObject.toJSONString(resultBean);
        resp.getWriter().write(resultJsonStr);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
